import React, { useState, useEffect, useCallback } from 'react';
import { Checkbox, Divider, Button } from 'antd';
import { MoreOutlined } from '@ant-design/icons';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import type { DropResult } from 'react-beautiful-dnd';

interface ColumnSetting {
  title: string;
  dataIndex: string;
  checked?: boolean;
  [key: string]: any;
}

interface ColumnSettingProps {
  columns: ColumnSetting[];
  onColumnChange: (columns: ColumnSetting[]) => void;
}

const ColumnSetting: React.FC<ColumnSettingProps> = ({
  columns,
  onColumnChange,
}) => {
  const [columnsSetting, setColumnsSetting] = useState<ColumnSetting[]>([]);
  const [checkAll, setCheckAll] = useState(true);
  const [indeterminate, setIndeterminate] = useState(false);
  const [originColumns, setOriginColumns] = useState<ColumnSetting[]>([]);

  // 初始化列设置
  useEffect(() => {
    const initializedColumns = columns.map((col) => ({
      ...col,
      checked: col.checked === undefined ? true : col.checked,
    }));

    setColumnsSetting(initializedColumns);
    setOriginColumns(initializedColumns.map((col) => ({ ...col })));

    const checkedCount = initializedColumns.filter((c) => c.checked).length;
    setCheckAll(checkedCount === initializedColumns.length);
    setIndeterminate(
      checkedCount > 0 && checkedCount < initializedColumns.length,
    );
  }, [columns]);

  // 重置列设置
  const handleReset = useCallback(() => {
    setColumnsSetting(originColumns.map((col) => ({ ...col })));
    setCheckAll(true);
    setIndeterminate(false);
    onColumnChange(originColumns);
  }, [originColumns, onColumnChange]);

  // 单个复选框变化
  const handleSingleChange = useCallback(
    (index: number) => {
      const newColumns = [...columnsSetting];
      newColumns[index].checked = !newColumns[index].checked;

      const checkedCount = newColumns.filter((c) => c.checked).length;
      setCheckAll(checkedCount === newColumns.length);
      setIndeterminate(checkedCount > 0 && checkedCount < newColumns.length);
      setColumnsSetting(newColumns);
      onColumnChange(newColumns);
    },
    [columnsSetting, onColumnChange],
  );

  // 全选/全不选
  const handleCheckAll = useCallback(
    (e: any) => {
      const checked = e.target.checked;
      const newColumns = columnsSetting.map((col) => ({ ...col, checked }));

      setCheckAll(checked);
      setIndeterminate(false);
      setColumnsSetting(newColumns);
      onColumnChange(newColumns);
    },
    [columnsSetting, onColumnChange],
  );

  // 处理拖拽排序
  const handleDragEnd = useCallback(
    (result: DropResult) => {
      if (!result.destination) return;

      const items = Array.from(columnsSetting);
      const [removed] = items.splice(result.source.index, 1);
      items.splice(result.destination.index, 0, removed);

      setColumnsSetting(items);
      onColumnChange(items);
    },
    [columnsSetting, onColumnChange],
  );

  return (
    <div className="ant-dropdown-menu s-tool-column ant-dropdown-content">
      <div className="s-tool-column-header s-tool-column-item">
        <Checkbox
          indeterminate={indeterminate}
          checked={checkAll}
          onChange={handleCheckAll}
        >
          列展示
        </Checkbox>
        <Button type="link" onClick={handleReset}>
          重置
        </Button>
      </div>
      <Divider style={{ margin: '8px 0' }} />

      <DragDropContext onDragEnd={handleDragEnd}>
        <Droppable droppableId="columns">
          {(provided) => (
            <div
              {...provided.droppableProps}
              ref={provided.innerRef}
              className="ant-checkbox-group"
            >
              {columnsSetting.map((col, index) => (
                <Draggable
                  key={col.dataIndex}
                  draggableId={col.dataIndex}
                  index={index}
                >
                  {(provided) => (
                    <div
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      className="s-tool-column-item"
                    >
                      <div
                        {...provided.dragHandleProps}
                        className="s-tool-column-handle layout-items-center"
                      >
                        <MoreOutlined style={{ transform: 'rotate(90deg)' }} />
                        <MoreOutlined style={{ transform: 'rotate(90deg)' }} />
                      </div>
                      <Checkbox
                        checked={col.checked}
                        onChange={() => handleSingleChange(index)}
                      >
                        {col.title}
                      </Checkbox>
                    </div>
                  )}
                </Draggable>
              ))}
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    </div>
  );
};

export default ColumnSetting;
